package com.humh.library.v2.model;

// 图书馆管理员类
import com.humh.library.model.Book;
import com.humh.library.model.InventoryManagement;
import com.humh.library.model.LoanRecord;
import com.humh.library.model.Reader;
import java.util.List;

public class Librarian {
  private String librarianId;
  private String name;
  private InventoryManagement inventoryManagement;
  private final int MAX_BORROWING_NUM = 5;  // 最大借书数量

  public Librarian(String librarianId, String name, InventoryManagement inventoryManagement) {
    this.librarianId = librarianId;
    this.name = name;
    this.inventoryManagement = inventoryManagement;
  }

  // 批量维护图书目录
  public void maintainCatalog(com.humh.library.model.Book book, int quantity) {
    inventoryManagement.addBookStock(book, quantity);
  }

  // 借阅图书
  public void manageBorrowing(com.humh.library.model.Reader reader, List<com.humh.library.model.Book> books) {
    if (reader.hasOverdueBooks()) {  //判断是否有超期图书
      System.out.println(reader.getName() + " has overdue books and cannot borrow until they are returned.");
      return;
    }

    if (books.size() > MAX_BORROWING_NUM) {  // 判断借书数量是否超过图书馆请允许的一个读者借书数量的最大值
      System.out.println(reader.getName() + " cannot borrow more than 5 books at a time.");
      return;
    }

    for (com.humh.library.model.Book book : books) {
      if (!inventoryManagement.isBookAvailable(book)) {  // 检查库存是否有足够副本
        System.out.println("Book " + book.getTitle() + " is not available for borrowing.");
        return;
      }
    }

    for (com.humh.library.model.Book book : books) {
      inventoryManagement.reduceBookStock(book);
      LoanRecord loanRecord = new LoanRecord(reader, book);
      reader.addLoanRecord(loanRecord);
      System.out.println(reader.getName() + " borrowed " + book.getTitle());
    }
  }

  // 归还图书
  public void manageReturning(com.humh.library.model.Reader reader, List<com.humh.library.model.Book> books) {
    for (com.humh.library.model.Book book : books) {
      LoanRecord record = findLoanRecord(reader, book);
      if (record == null) {  // 未找到借阅记录
        System.out.println("No record of " + reader.getName() + " borrowing " + book.getTitle());
        continue;
      }

      if (record.isOverdue()) {  // 判断是否超期
        double fineAmount = record.calculateFine();
        if (!reader.payFine(fineAmount)) {  //是否成功支付罚款
          System.out.println(reader.getName() + " has an overdue fine of $" + fineAmount + " for " + book.getTitle() + ". Fine must be paid before returning.");
          return;
        }
      }

      inventoryManagement.returnBookStock(book);
      System.out.println(reader.getName() + " returned " + book.getTitle());
    }
  }

  // 查找借书记录
  private LoanRecord findLoanRecord(Reader reader, Book book) {
    for (LoanRecord loanRecord : reader.getLoanRecords()) {
      if (loanRecord.getBook().equals(book)) {
        return loanRecord;
      }
    }
    return null;
  }
}

